class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        //定义虚拟节点
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode prev = newHead;
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            ListNode next = cur.next; // next指向当前节点的下一个节点
            // 交换节点
            cur.next = next.next; // 当前节点的next指向next的next
            next.next = cur; // next的next指向当前节点
            prev.next = next; // prev的next指向next，从而完成交换

            // 更新prev和cur
            prev = cur; // prev移动到cur
            cur = cur.next; // cur移动到下一个待交换的节点
        }
        return newHead.next;
    }
}

public class Test01 {
    public static void main(String[] args) {

    }
}
